package com.itheima.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.entity.Employee;
import com.itheima.service.IEmployeeService;
import com.itheima.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/employee")
@Validated
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 员工登录
     * @param employee :用户输入的账号和密码
     * @return :返回登录当前用户的用户名
     */
    @PostMapping("/login")
    public Result login( @RequestBody Employee employee){
        return employeeService.login(employee);
    }

    /**
     * 添加用户
     * @param employee ：添加用户的信息
     * @return ：返回是否添加成功的消息
     */
    @PostMapping
    public Result saveEmployee(@Valid @RequestBody Employee employee,BindingResult br){
        if (br.hasErrors()){
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError err: allErrors) {
                FieldError fieldError = (FieldError) err;
                System.out.println(fieldError.getDefaultMessage());
            }
            return Result.error("参数异常");
        }
        return employeeService.saveEmployee(employee);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Long id){
        return employeeService.findOne(id);
    }

    @PutMapping
    public Result updateOne(@RequestBody Employee employee){
        return employeeService.updateOne(employee);
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return employeeService.logout();
    }

    @GetMapping("/page")
    public Result getPage(@RequestParam(value = "page") int page, @RequestParam(value = "pageSize")  int pageSize,@RequestParam(value = "name" ,required = false) String name){
        IPage employeeServicePage = employeeService.getPage(page, pageSize ,name);
        if (page >employeeServicePage.getPages()){
            employeeServicePage = employeeService.getPage((int) employeeServicePage.getPages(), pageSize ,name);
        }
        return Result.success(employeeServicePage);
    }

}
